<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\model\Attachment;
use think\exception\HttpResponseException;
use think\facade\View;
use think\response\Json;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;


class AdminBase extends BaseController
{
    protected const _ALLOW_PICTURE_EXT = ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'svg'];  // 允许上传的图片格式
    protected const _ALLOW_FILE_EXT    = ['doc', 'docx', 'xls', 'xlsx', 'zip', 'rar', 'tar', '7z', 'gz', 'txt','pdf']; // 允许上传的文件格式
    protected $websiteCode  = '';
    protected $cdnDomain    = '';
    protected $cdnBucket    = '';
    protected $cdnAccessKey = '';
    protected $cdnSecretKey = '';

    public function initialize()
    {
        parent::initialize();
        $this->_manageWebsite();
    }

    public function show(...$args)
    {
        throw new HttpResponseException(show(...$args));
    }

    private function _manageWebsite()
    {
        if (!file_exists('../install.lock')) {
            return $this->redirect((string)url('install/index/index'));
        }

        // 校验是否有权限访问这个路由
        $merchantUserObj = new \app\platform\business\Merchant();
        $merchant        = $merchantUserObj->getMerchantUserFromSession();
        $menuBusiness    = new \app\common\business\Menu();
        $roleIds         = $merchant['roleIds']??[];
        $actions         = $menuBusiness->getLoginRolPermissionActions($roleIds);
        $requestPath     = '/admin/' . $this->request->pathinfo();
        if (!strstr($requestPath, 'permission') && !in_array($requestPath, $actions['actionPaths'])) {
            // dump(in_array($requestPath,$actions['actionPaths']));
            // dump($actions['actionPaths']);
            // echo $requestPath;exit;
            if ($this->request->isPost()) {
                return $this->show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PERMISSION_DENY_MESSAGE);
            } else {
                return $this->redirect((string)url('permission/msg', ['website_code' => $this->websiteCode]));
            }
        }

        // 校验是否有权限访问这个站点
        $websiteBusiness   = new \app\admin\business\Website();
        $this->websiteCode = $this->request->param('website_code', '', 'trim');
        $website           = $websiteBusiness->findWebsiteByCode($this->websiteCode);
        if (!$websiteBusiness->checkPermissionToOperateWebsite($website)) {
            if ($this->request->isPost()) {
                return $this->show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PERMISSION_DENY_MESSAGE);
            } else {
                return $this->redirect((string)url('platform/index/index'));
            }
        }

        $this->cdnDomain    = $website['cdn_domain'];
        $this->cdnBucket    = $website['cdn_bucket'];
        $this->cdnAccessKey = env('qiniu.ACCESS_KEY');
        $this->cdnSecretKey = env('qiniu.SECRET_KEY');
        View::assign([
            'websiteName' => $website['name'],
            'websiteCode' => $this->websiteCode,
            'frontedUrl'  => $website['frontend_url'],
            'actions'     => $actions['menuCodes'],
        ]);
    }

    public function redirect(...$args)
    {
        throw new HttpResponseException(redirect(...$args));
    }

    protected function _upload(string $fieldName, array $allowExt): array
    {
        if ($this->cdnBucket && $this->cdnDomain && $this->cdnAccessKey && $this->cdnSecretKey) {
            return $this->_uploadToCdn($fieldName, $allowExt);
        }

        return $this->_uploadToLocal($fieldName, $allowExt);
    }

    protected function _uploadToCdn(string $fieldName, array $allowExt): array
    {
        $files = $_FILES[$fieldName];
        if (empty($files)) {
            return ['error' => config(self::_CONFIG_STATUS_ERROR_CODE), 'path' => ''];
        }

        $ext = substr(strrchr($files['name'], '.'), 1);

        // 校验上传文件格式
        if (!in_array($ext, $allowExt)) {
            return ['error' => config(self::_CONFIG_STATUS_ERROR_CODE), 'path' => ''];
        }

        $fileName = $this->websiteCode . '/' . date('Ymd', time()) . '/' . date('YmdHis', time()) . rand(100, 999) . '.' . $ext;
        $fullPath = $this->cdnDomain . "/" . $fileName;

        $auth      = new Auth($this->cdnAccessKey, $this->cdnSecretKey);
        $token     = $auth->uploadToken($this->cdnBucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $fileName, $_FILES[$fieldName]['tmp_name']);
        if ($err !== null) {
            return ['error' => config(self::_CONFIG_STATUS_ERROR_CODE), 'path' => ''];
        }

        $attachmentBusiness = new \app\admin\business\Attachment($this->websiteCode);
        $attachmentBusiness->addAttachment(['title' => basename($fileName), 'url' => $fileName, 'url_md5' => md5($fileName)]);

        return ['error' => config(self::_CONFIG_STATUS_SUCCESS_CODE), 'path' => $fileName, 'fullPath' => $fullPath, 'title' => $files['name']];
    }

    protected function _uploadToLocal(string $fieldName, array $allowExt): array
    {
        $files = $_FILES[$fieldName];
        if (empty($files)) {
            return ['error' => config(self::_CONFIG_STATUS_ERROR_CODE), 'path' => ''];
        }

        $ext = substr(strrchr($files['name'], '.'), 1);

        // 校验上传文件格式
        if (!in_array($ext, $allowExt)) {
            return ['error' => config(self::_CONFIG_STATUS_ERROR_CODE), 'path' => ''];
        }

        // 创建目录
        $dirName = 'upload/' . $this->websiteCode . '/' . date('Ymd', time());
        is_dir('./' . $dirName) || mkdir('./' . $dirName, 0777, true);

        // 移动文件
        $fileName = $dirName . '/' . date('YmdHis', time()) . rand(100, 999) . '.' . $ext;
        move_uploaded_file($_FILES[$fieldName]['tmp_name'], './' . $fileName);

        $attachmentBusiness = new \app\admin\business\Attachment($this->websiteCode);
        $attachmentBusiness->addAttachment(['title' => basename($fileName), 'url' => $fileName, 'url_md5' => md5($fileName)]);

        return ['error' => config(self::_CONFIG_STATUS_SUCCESS_CODE), 'path' => $fileName, 'fullPath' => '/' . $fileName, 'title' => $files['name']];
    }

    public function upload(): Json
    {
        $res = $this->_upload('file', array_merge(self::_ALLOW_PICTURE_EXT, self::_ALLOW_FILE_EXT));
        if ($res['error'] == config(self::_CONFIG_STATUS_ERROR_CODE)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_UPLOAD_ERROR_MESSAGE);
        }

        return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), self::_UPLOAD_SUCCESS_MESSAGE, ['path' => $res['path'], 'fullPath' => $res['fullPath'], 'title' => $res['title']]);
    }

    public function kindEditorUpload(): Json
    {
        $res = $this->_upload('imgFile', self::_ALLOW_PICTURE_EXT);
        if ($res['error'] == config(self::_CONFIG_STATUS_ERROR_CODE)) {
            return json(['error' => config(self::_CONFIG_STATUS_ERROR_CODE), 'message' => self::_UPLOAD_ERROR_MESSAGE]);
        }

        return json(['error' => config(self::_CONFIG_STATUS_SUCCESS_CODE), 'url' => $res['fullPath']]);
    }
}
